#include <iostream>
#include <sys/socket.h>
#include <unistd.h>
#include <string>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
using namespace std;


class Udp_Client
{
public:
    Udp_Client(uint16_t port, string ip)
        : _sockfd(-1), _port(port), _ip(ip)
    {}


    void start()
    {
        string msg;
        struct sockaddr_in client;
        memset(&client, '\0', sizeof(client));
        client.sin_family = AF_INET;
        client.sin_port = htons(_port);
        client.sin_addr.s_addr = inet_addr(_ip.c_str());

        for (;;)
        {
            cout << "Place Enter# ";
            getline(cin, msg);
            sendto(_sockfd, &msg, msg.size(), 0, (sockaddr *)&client, sizeof(client));
        }

#define SIZE 128
        char buff[128];
        struct sockaddr_in tmp;
        socklen_t len = sizeof(tmp);
        ssize_t ret = recvfrom(_sockfd, buff, sizeof(buff)-1, 0, (sockaddr*)&tmp, &len);
        if(ret >= 0)
        {
            buff[SIZE] = '\0';
            cout << buff << endl;
        }
        
    }

   bool Init_client()
   {
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if(_sockfd < 0)
        {
            cerr << "sock fail!" << _sockfd << endl;
            return false;
        }
        cout << "sock success !" << endl;
        return true;
   }

private:
    int _sockfd;
    string _ip;
    uint16_t _port;
};

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        // 客户端传递服务端的ip和port.
        cerr << "Usage: " << argv[0] << "Server_ip and Servert_port" << endl;
        return 1;
    }

    string server_ip = argv[1];
    int server_port = atoi(argv[2]);
    Udp_Client *res = new Udp_Client(server_port, server_ip); 
    res->Init_client();
    res->start();
    return 0;
}